package com.wlt.controller;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.wlt.domain.User;
import com.wlt.service.UserService;

@Controller
@RequestMapping("/user")
//这里用了@SessionAttributes，可以直接把model中的user(也就key)放入其中
//这样保证了session中存在user这个对象
@SessionAttributes("user")
public class UserController {
	@Autowired
	private UserService userService;
	
	//正常访问login页面
	@RequestMapping("/index")
	public String login() {
		return "index";
	}
	/**
	 * 查询用户
	 * @param map
	 * @return
	 */
	@RequestMapping("/list")
	public String list(ModelMap map) {
		map.addAttribute("list",userService.list());
		return "/list";
		
	}
	//表单提交过来的路径
	@RequestMapping("/checkLogin")
	public String checkLogin(User user,Model model) {
		//调用service方法
		user=userService.checkLogin(user.getUserName(),user.getPassword());
		//假如有user 则添加到model里并且跳转到成功页面
		if(user != null) {
			model.addAttribute("user",user);
			return "/list";
		}
		return "index";
	}
	//测试超链接跳转到另一个页面是否可以取到session值
    @RequestMapping("/anotherpage")
    public String hrefpage(){
        return "anotherpage";
    }
    //注销
    @RequestMapping("/outLogin")
    public String outLogin(HttpSession session){
        //通过session.invalidata()方法来注销当前的session
        session.invalidate();
        return "index";
    }
    @RequestMapping("/regist")
    public String regist(){
        return "regist";
    }

    @RequestMapping("/doRegist")
    public String doRegist(User user,Model model){
        System.out.println(user.getUserName());
		userService.Regist(user);
        return "redirect:list.do";
    }
    //增加用户
    @RequestMapping("/add")
	public String add(User user) {
		userService.addUser(user);
		return "redirect:list.do";
	}
    //删除用户
    @RequestMapping(value="/{id}/delete")
	public String delete(@PathVariable int id) {
		System.out.println(id);
		userService.deleteByUserId(id);
		return "redirect:/user/list.do";
	}

}
